package com.clkj.mobileinspector.ui.fragment;

import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.clkj.mobileinspector.R;
import com.clkj.mobileinspector.model.Constant;
import com.clkj.mobileinspector.model.ObserverOnNext;
import com.clkj.mobileinspector.model.OkHttpUtils;
import com.clkj.mobileinspector.model.bean.PolicedeptBean;
import com.clkj.mobileinspector.model.bean.ProblemtypeBean;
import com.clkj.mobileinspector.model.bean.QueryBean;
import com.clkj.mobileinspector.model.bean.QuerySuccessBean;
import com.clkj.mobileinspector.model.bean.ResourceApi;
import com.clkj.mobileinspector.ui.activity.MainActivity;
import com.clkj.mobileinspector.ui.activity.StatisticsActivity;
import com.clkj.mobileinspector.utils.JsonUtils;
import com.clkj.mobileinspector.utils.LogUtils;
import com.clkj.mobileinspector.utils.ResourceApiUtils;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.gson.reflect.TypeToken;
import com.lws.basic.base.BaseFragment;
import com.lws.basic.utils.common.GsonUtils;
import com.lws.basic.utils.common.MyLogger;
import com.lws.basic.utils.common.MyToast;
import com.lws.basic.utils.common.TimeUtils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.clkj.mobileinspector.utils.JsonUtils.queryGetFiled;

/**
 * @author 松
 * 2020/10/7 10:49
 * 问题占比
 */
public class ProblemFragment extends BaseFragment {
    Unbinder mUnbinder;
    @BindView(R.id.et_start)
    EditText mEtStart;
    @BindView(R.id.et_end)
    EditText mEtEnd;
    @BindView(R.id.sp_type)
    Spinner mSpUnit;
    @BindView(R.id.pieChart)
    PieChart mPieChart;
    private String mPolicedepId;//局id


    @Override
    public int setLayoutId() {
        return R.layout.fragment_problem;
    }

    @Override
    protected void initView(View rootView) {
        super.initView(rootView);
        mUnbinder = ButterKnife.bind(this, rootView);
    }

    @Override
    protected void initData() {
        super.initData();
        initSpinner(((StatisticsActivity) getActivity()).getSpList());
        getData(search());
        //initPie();
    }

    /**
     * 获取数据
     */
    private void getData(List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> keyValueListBeanList) {
        ResourceApi problemContrastChart= ResourceApiUtils.getResourceApi(MainActivity.resourceApiList, Constant.problemContrastChart);


        showLoading();
        List<QueryBean.ParameterBean.OrderByBean> orderByList = new ArrayList<>();
//        QueryBean.ParameterBean.OrderByBean order1 = new QueryBean.ParameterBean.OrderByBean();
//        order1.setSort("passdate");
//        order1.setSort("desc");
//        orderByList.add(order1);

        QueryBean.ParameterBean.PageBean page = new QueryBean.ParameterBean.PageBean();
        page.setPageNo(1);
        page.setPageSize(1000);

        String json = JsonUtils.query(keyValueListBeanList, "problemname,inspectiontotal"
                , problemContrastChart.getResourceId(), orderByList, page, problemContrastChart.getResourceRegionalismCode());
        LogUtils.logUpload("问题占比", "1",problemContrastChart.getResourceId(), problemContrastChart.getResourceAddress(), json, "", "成功", "","");

        OkHttpUtils.post(problemContrastChart.getResourceAddress(), json, QuerySuccessBean.class).subscribe(new ObserverOnNext<QuerySuccessBean>() {
            @Override
            public void onNext(QuerySuccessBean querySuccessBean) {
                dismissLoading();

                if (querySuccessBean.getCode().equals("200")) {

                    initPie(querySuccessBean.getData().getDataList());
                } else {
                    MyToast.show(querySuccessBean.getMessage());
                }
            }
        });
    }


    /**
     * 搜索条件
     */
    private List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> search() {
        String start = mEtStart.getText().toString();//
        String end = mEtEnd.getText().toString();//
        if (!TextUtils.isEmpty(end)){
            end+=" 23:59:59";
        }
        List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> list = new ArrayList<>();

        if (!mPolicedepId.equals("0")) {
            QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean2 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
            bean2.setKey("firstleveldutyunit");
            bean2.setRelationOperator("=");
            bean2.setValue(mPolicedepId);
            list.add(bean2);
        }
        QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean3 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
        bean3.setKey("starttime");
        bean3.setRelationOperator(">=");
        bean3.setValue(start);
        list.add(bean3);
        QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean4 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
        bean4.setKey("endtime");
        bean4.setRelationOperator("<=");
        bean4.setValue(end);
        list.add(bean4);
        return list;
    }


    /**
     * 初始化下拉列表
     */
    private void initSpinner(List<QuerySuccessBean.DataBean.DataListBean.FieldValuesBean> list) {
        try {


            //局
            String policedept = JsonUtils.queryGetFiled(list, "policedept");
            Type policedeptType = new TypeToken<List<PolicedeptBean>>() {
            }.getType();
            List<PolicedeptBean> policedeptBeanList = GsonUtils.getInstance().fromJson(policedept, policedeptType);
            List<String> policedeptList = new ArrayList<>();
            policedeptList.add("全部");
            for (PolicedeptBean bean : policedeptBeanList) {
                policedeptList.add(bean.getName());
            }
            mPolicedepId = "0";

            //局
            ArrayAdapter adapterUnit = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, policedeptList);
            mSpUnit.setAdapter(adapterUnit);
            mSpUnit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                    if (position == 0) {
                        mPolicedepId = "0";

                    } else {
                        mPolicedepId = policedeptBeanList.get(position - 1).getDeptid() + "";

                    }

                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
        } catch (Exception e) {
            MyToast.show(e.getMessage());
            MyLogger.i("统计分析下拉列表" + e.getMessage());
        }


    }





    private void initPie(List<QuerySuccessBean.DataBean.DataListBean> list) {

        mPieChart.setUsePercentValues(true);
        mPieChart.getDescription().setEnabled(false);

        mPieChart.setExtraOffsets(0, 10, 5, 5);

        mPieChart.setDrawEntryLabels(false);

        mPieChart.setDragDecelerationFrictionCoef(0.95f);

        mPieChart.setDrawHoleEnabled(false); //不显示中间
        //pieChart.setHoleColor(Color.WHITE);

        mPieChart.setCenterTextColor(Color.WHITE); //中间文字颜色
        mPieChart.setDrawCenterText(true); //是否显示中间文字
        //mPieChart.setCenterText("点击查看详情");


        mPieChart.setRotationAngle(0);
        // 触摸旋转
        mPieChart.setRotationEnabled(true);
        mPieChart.setHighlightPerTapEnabled(true);

        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
        for (QuerySuccessBean.DataBean.DataListBean bean :list) {

            if (!TextUtils.isEmpty(queryGetFiled(bean.getFieldValues(), "inspectiontotal"))) {

                entries.add(new PieEntry(Integer.valueOf(queryGetFiled(bean.getFieldValues(), "inspectiontotal")),queryGetFiled(bean.getFieldValues(), "problemname") ));

            }

        }



        //下标说明
        Legend l = mPieChart.getLegend();
        l.setEnabled(true);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setXEntrySpace(17f);
        l.setYEntrySpace(0f);
        l.setTextSize(14);


        // 输入标签样式
        mPieChart.setEntryLabelColor(Color.BLACK);
        mPieChart.setEntryLabelTextSize(12f);


        PieDataSet dataSet = new PieDataSet(entries, "");
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(7f);//选中饼块 放大

        //数据和颜色
        ArrayList<Integer> colors = new ArrayList<Integer>();
        colors.add(getResources().getColor(R.color.color_main));
        colors.add(getResources().getColor(R.color.yellow_fa8c35));
        colors.add(getResources().getColor(R.color.red_622a1d));
        colors.add(getResources().getColor(R.color.gray_666666));
        colors.add(getResources().getColor(R.color.green));
        colors.add(getResources().getColor(R.color.yellow_ffd700));
        colors.add(getResources().getColor(R.color.black_333333));

        colors.add(ColorTemplate.getHoloBlue());
        dataSet.setColors(colors);
        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter(mPieChart));

        data.setValueTextSize(14f);
  /*      dataSet.setValueLinePart1Length(0.6f);
//      当值位置为外边线时，表示线的后半段长度。
        dataSet.setValueLinePart2Length(0.3f);*/
//      当ValuePosits为OutsiDice时，指示偏移为切片大小的百分比
        // dataSet.setValueLinePart1OffsetPercentage(80f);

        /*dataSet.setValueLinePart1OffsetPercentage(100.f);
        dataSet.setValueLinePart1Length(1f);
        dataSet.setValueLinePart2Length(0.6f);
        // dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setValueLineWidth(2);*/

        dataSet.setYValuePosition(PieDataSet.ValuePosition.INSIDE_SLICE); //
        data.setValueTextColor(Color.WHITE);
        mPieChart.setData(data);
      /*  pieChart.highlightValues(null);
        pieChart.setDrawHoleEnabled(false);*/
        // mPieChart.setUsePercentValues(false);
        //刷新
        mPieChart.invalidate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }
    @OnClick({R.id.et_start, R.id.et_end, R.id.btn_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_start:
                showTime(1);
                break;
            case R.id.et_end:
                showTime(2);
                break;
            case R.id.btn_search:
                getData(search());
                break;
        }
    }

    /**
     * 显示时间
     */
    private void showTime(int flag) {
        TimePickerView pvTime = new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String time = TimeUtils.date2date(date);
                //1开始时间
                if (flag == 1) {
                    mEtStart.setText(time);
                }
                //结束时间
                if (flag == 2) {
                    mEtEnd.setText(time);
                }

                MyLogger.i(TimeUtils.date2date(date));

            }
        }).setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setBgColor(0xffd6ecf0)
                .setTitleBgColor(0xffd6ecf0)
                .setLabel("年", "月", "日", "", "", "")//默认设置为年月日时分秒
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();

        pvTime.show();
    }


}
